package com.hnblc.blcwms.rest.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnblc.blcwms.common.constant.StringPool;
import com.hnblc.blcwms.common.exceptions.ErrorDescription;
import com.hnblc.blcwms.common.exceptions.GeneralException;
import com.hnblc.blcwms.common.utils.FileUtils;
import com.hnblc.blcwms.common.utils.OsSystemUtils;
import com.hnblc.blcwms.common.utils.WmsTimeUtils;
import com.hnblc.blcwms.persistent.interfaces.client.entity.ClientInfo;
import com.hnblc.blcwms.persistent.interfaces.message.entity.MessageLog;
import com.hnblc.blcwms.persistent.interfaces.message.service.IMessageLogService;
import com.hnblc.blcwms.persistent.interfaces.message.service.impl.MessageLogServiceImpl;
import com.hnblc.blcwms.persistent.interfaces.sysConfig.entity.FieldDictionary;
import com.hnblc.blcwms.persistent.interfaces.sysConfig.service.IFieldDictionaryService;
import com.hnblc.blcwms.rest.service.IMessageService;
import com.hnblc.blcwms.serviceapi.api.enums.result.log.MessageLogResultEnum;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Map;

@Getter
@Setter
@Service
public class MessageService implements IMessageService {

    @Autowired
    private IMessageLogService messageLogService;


    @Autowired
    private IFieldDictionaryService fieldDictionaryService;

    @Autowired
    private ObjectMapper objectMapper;

    private Logger logger = LoggerFactory.getLogger(MessageLogServiceImpl.class);



    @Override
    public MessageLog process(ClientInfo clientInfo, HttpServletRequest request) {

        //请求对象转换为JSON字符串，为了保存文件
        String jsonString;
        try {
            jsonString = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
            logger.debug("***********************************test start***************************\n"+jsonString+"*********************end*************************");
        }catch(IOException jpe){
            GeneralException e = new GeneralException(jpe);
            logger.error(e.getCode()+e.getLocalizedMessage() +jpe.getMessage(),jpe);
            throw  e;
        }
        if (jsonString==null){
            GeneralException e = new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0);
            logger.error(e.getCode()+e.getLocalizedMessage(),e);
            throw e;
        }

        //将接口请求的数据写入文件
        String filePath = OsSystemUtils.getOsInterfacePath()+ File.separator+ WmsTimeUtils.getCurrentDatetime(WmsTimeUtils.TimeFormat.SHORT_DATE_PATTERN_NONE) +File.separator+clientInfo.getClientId()+File.separator;
        File dir = new File(filePath);
        if(!dir.exists() || dir.isFile()){
            dir.mkdirs();
        }
        String fileName = filePath+System.currentTimeMillis()+StringPool.FILE_SUFFIX_DOT_TXT;
        FileUtils.createFile(fileName);
        FileUtils.writeToFile(fileName,jsonString , true);
        //持久化消息记录
        //处理状态字典：1：未处理，2，处理成功，0，处理失败。
        Map<String, FieldDictionary> fieldDictionaries = fieldDictionaryService.mapLoadInCache("I_M_MESSAGE_LOG","PROCESS_STATUS");
        MessageLog messageLog = new MessageLog();
        messageLog.setReceiveDate(LocalDateTime.now());
        messageLog.setSendClientId(clientInfo.getClientId());
        messageLog.setMessageFile(fileName);
        messageLog.setProcessStatus(MessageLogResultEnum.UNPROCESSED.code());

        boolean saveResult = messageLogService.save(messageLog);
        if (saveResult){
            logger.debug("messageLog save success messageId:"+messageLog.getSeqNo());
        }
        return messageLog;
    }

    @Override
    public boolean processed(MessageLog messageLog) {
        messageLog.setProcessStatus(MessageLogResultEnum.PROCESSED.code());
        return messageLogService.updateById(messageLog);
    }


}
